<template>
	<view class="al-tabs">
		<scroll-view scroll-x="true" class="al-scroll-view" :scroll-left="scrollLeft" scroll-with-animation>
			<view class="al-tab-item" v-for="(item,index) in list" :key="index" @tap="clickTab(index)">
				<text :class="{'tab-active':currentIndex == index}">{{item.name}}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name:"al-tabs",
		props:{
			list: {
				type: Array,
				default () {
					return [];
				}
			},
			current: {
				type: [Number, String],
				default: 0
			},
		},
		data() {
			return {
				currentIndex:0,
				scrollLeft: 0, // 滚动scroll-view的左边滚动距离
				componentWidth: 0, // 屏幕宽度，单位为px
				parentLeft: 0, // 父元素(tabs组件)到屏幕左边的距离
				tabQueryInfo: [],
			}
		},
		watch:{
			list(n,o){
				this.$nextTick(function(){
					this.scrollInit()
				})
			},
			current: {
				immediate: true,
				handler(nVal, oVal) {
					// 视图更新后再执行移动操作
					this.$nextTick(() => {
						this.currentIndex = nVal;
						this.scrollByIndex();
					});
				}
			},
		},
		mounted() {
			this.scrollInit()
		},
		methods: {
			clickTab(index){
				if(this.currentIndex !=index){
					this.currentIndex=index
					this.$emit('change',index)
				}
			},
			scrollInit(){
				let query = uni.createSelectorQuery().in(this);
				//获取tab栏所有标签节点
				query.selectAll('.al-tab-item').fields({
					size: true,
					rect: true
				});
				query.exec((res=>{
					this.tabQueryInfo=res[0]
				}))
				query.select('.al-tabs').boundingClientRect(data => {
					this.componentWidth=data.left+data.right
				}).exec()
			},
			scrollByIndex() {
				// 当前活动tab的布局信息，有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
				if(!this.tabQueryInfo){
					this.scrollInit()
				}
				let tabInfo = this.tabQueryInfo[this.currentIndex];
				if (!tabInfo) return;
				// 活动tab的宽度
				let tabWidth = tabInfo.width;
				// 活动item的左边到tabs组件左边的距离，用item的left减去tabs的left
				let offsetLeft = tabInfo.left - this.parentLeft;
				// 将活动的tabs-item移动到屏幕正中间，实际上是对scroll-view的移动
				let scrollLeft = offsetLeft - (this.componentWidth - tabWidth) / 2;
				this.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.al-tabs{
		font-size: 28rpx;
	}
	.al-scroll-view{
		width: 100%;
		white-space: nowrap;
		box-sizing: border-box;
		touch-action: none;
		.al-tab-item{
			display: inline-block;
			padding:0 20rpx 20rpx;
			text-align: center;
			position: relative;
		}
		.tab-active{
			font-weight: bold;
			padding-bottom: 8rpx;
			border-bottom: 3px solid #fff;
			border-bottom-left-radius: 2px;
			border-bottom-right-radius: 2px;
			transition: border 0.1s;
		}
	}
	
	// 隐藏scroll-view下的滚动条
	scroll-view ::v-deep ::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
</style>
